import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import classnames from 'classnames';
import { Seq } from 'immutable';
import {immutableRenderDecorator } from 'react-immutable-render-mixin';
import PropTypes from 'prop-types';

import styles from './Tabs.scss';
import TabNav from './TabNav';
import TabContent from './TabContent';

@immutableRenderDecorator
@CSSModules(styles, { allowMultiple: true})
class Tabs extends Component {

  static propTypes = {
    prefixClass: PropTypes.string,
    onChange: PropTypes.func,
  }

  static defaultProps = {
    onChange: () => {},
  }

  constructor(props) {
    super(props);
    let activeIndex;
    this.onTabClick = this.onTabClick.bind(this);
    this.immChildren = Seq(props.children);

    if (props.hasOwnProperty('activeIndex')) {
      activeIndex = props.activeIndex;
    } else if (props.hasOwnProperty('defaultIndex')) {
      activeIndex = props.defaultIndex;
    }
    this.state = {
      activeIndex,
    }
  }
  renderTabNav() {
    const { activeIndex } = this.state;
    const { prefixClass } = this.props;
    return (
      <TabNav
        key="tabNav"
        activeIndex={activeIndex}
        panels={this.immChildren}
        prefixClass={prefixClass}
        onTabClick={this.onTabClick}
      />
    )
  }
  renderTabContent() {
    const { activeIndex } = this.state;
    const { prefixClass } = this.props;
    return (<TabContent
      key="tabContent"
      activeIndex={activeIndex}
      panels={this.immChildren}
      prefixClass={prefixClass}
    />)
  }

  onTabClick(index) {
    const { onChange } = this.props;
    if (this.state.activeIndex !== index) {
      this.setState({
        activeIndex: index,
        prevIndex: this.state.activeIndex,
      })
    }
    onChange(index);
  }
  render() {
    const { prefixClass } = this.props;
    const classes = classnames({
      [prefixClass]: true,
    })
    return (
      <div styleName={classes}>
        { this.renderTabNav() }
        { this.renderTabContent()}
      </div>
    )
  }
}

export default Tabs;
